<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<br><br>
<div class="re-box" id="comment-box">
    <%---------------- 编辑器 ----------------%>
    <br>
    <div class="row">
        <div class="col-12">
            <div id="editor" autofocus></div>
        </div>
    </div>
    <button id="submitCommentButton" class="re-btn re-label-child pull-right"
            onclick="submitRichComment()">
        发表评论
    </button>
    <br><br><br>
    <div class="resource-comment" id="comment-title">
        <h6 class="font-2">评论</h6>
        <c:if test="${commentList.size() == 0}">
            <div class="font-text-darkgray">
                此资源暂无评论~
            </div>
        </c:if>
    </div>
    <c:forEach var="com" items="${commentList}">
        <div class="resource-comment" id="${com.id}">
            <div class="col-lg-12">
                    <%---------------------- 评论头像 ----------------------%>
                <div class="resource-comment-img">
                    <img src="/assets/images/profilePic/${com.picName}">
                </div>
                <%---------------------- 评论内容 ----------------------%>
                <div class="resource-comment-cont">
                    <%---------------------- 评论操作 ----------------------%>
                    <span style="float: right; top: -6px;">
                        <c:if test="${com.userId == userId}">
                            <a type="button" class="resource-comment-linkButton font-text-darkgray"
                               style="text-align: right;text-decoration: underline" onclick="doEdit(${com.id})">
                                编辑
                            </a>
                            <div style="display:inline-block; font-size: 1rem">
                                &nbsp|&nbsp
                            </div>
                            <a type="button" class="resource-comment-linkButton font-text-darkgray"
                               style="text-align: right;text-decoration: underline" onclick="deleteComment(${com.id})">
                                删除
                            </a>
                            <div style="display:inline-block; font-size: 1rem">
                                &nbsp|&nbsp
                            </div>
                        </c:if>
                        <a type="button" class="resource-comment-linkButton font-text-darkgray"
                           style="float: right;text-decoration: underline" id="comment-foldOn-upper-${com.id}"
                           href="javascript:doFold(0, ${com.id})" style="display: block">折叠</a>
                        <a type="button" class="resource-comment-linkButton font-text-darkgray"
                           style="float: right;text-decoration: underline" id="comment-foldOff-upper-${com.id}"
                           href="javascript:doFold(1, ${com.id})" style="display: none">展开</a>
                    </span>
                    <div class="resource-comment-head row">
                            <%---------------------- 评论用户 ----------------------%>
                        <a href="/myresource?userId=${com.userId}" class="resource-comment-name"
                           id="comment-username-${com.id}">${com.userName}</a>
                    </div>
                        <%-- 正常显示 --%>
                    <div class="resource-comment-text" id="comment-content-${com.id}">
                            ${com.content}
                    </div>
                        <%-- 折叠显示 --%>
                    <div class="resource-comment-text resource-comment-gradient" style="display: none;" id="comment-min-${com.id}">
                    </div>
                        <%-- 时间-编辑-折叠按钮 --%>
                    <div class="resource-comment-date row" id="comment-bottomOff-${com.id}">
                        <fmt:formatDate value="${com.time}" pattern="yyyy-MM-dd HH:mm:ss"/>
                    </div>
                    <span style="float: right; top: -6px;; display: none" id="comment-links-lower-${com.id}">
                        <c:if test="${com.userId == userId}">
                            <a type="button" class="resource-comment-linkButton font-text-darkgray"
                               style="text-align: right;text-decoration: underline" onclick="doEdit(${com.id})">
                                编辑
                            </a>
                            <div style="display:inline-block; font-size: 1rem">
                                &nbsp|&nbsp
                            </div>
                            <a type="button" class="resource-comment-linkButton font-text-darkgray"
                               style="text-align: right;text-decoration: underline" onclick="deleteComment(${com.id})">
                                删除
                            </a>
                            <div style="display:inline-block; font-size: 1rem">
                                &nbsp|&nbsp
                            </div>
                        </c:if>
                        <a type="button" class="resource-comment-linkButton font-text-darkgray"
                           style="float: right;text-decoration: underline" id="comment-foldOn-lower-${com.id}"
                           href="javascript:doFold(0, ${com.id})" style="display: block">折叠</a>
                        <a type="button" class="resource-comment-linkButton font-text-darkgray"
                           style="float: right;text-decoration: underline" id="comment-foldOff-lower-${com.id}"
                           href="javascript:doFold(1, ${com.id})" style="display: none">展开</a>
                    </span>
                </div>
            </div>
            <div class="resource-comment-editor" id="comment-editor-${com.id}" style="display: none">
                <br>
                <textarea id="comment-editor-box-${com.id}">${com.content}</textarea>
                <button id="updateCommentButton-${com.id}" class="re-btn re-label-child pull-right"
                        onclick="updateComment(${com.id})">更新评论</button>
                <button id="updateCommentButton-${com.id}" class="re-btn re-label-child pull-right"
                        style="background-color: #adb5bd !important"
                        onclick="doEdit(${com.id})">退出编辑</button>
                <br><br>
            </div>
        </div>
    </c:forEach>
    <%---------------- 分页 ----------------%>
    <br>
    <div id="page-data" class="text-center">
        <div id="page-total" style="display: none">${pageTotal}</div>
    </div>
</div>

<%-- tinymce --%>
<script src="../assets/vendor/tinymce/tinymce.min.js"></script>

<script type="text/javascript">

    function initTinymce() {
        tinymce.init({
            selector: '#editor',
            contextmenu: "bold copy | link | image | imagetools | table | spellchecker",//上下文菜单
            auto_focus: false,
            menubar: false,
            language: 'zh_CN',
            // force_br_newlines: true,
            // force_p_newlines: false,
            // forced_root_block: "",
            // preformatted: true,
            toolbar_mode: 'sliding',
            branding: false,
            content_style: "img {height:auto;max-width:100%;max-height:100%;}",
            editor_selector: "editor-tinymce",
            plugins: [
                'powerpaste', // plugins中，用powerpaste替换原来的paste
                'image',
                "autoresize",
                "code",
                "link",
                "charmap",
                "emoticons",
                "table",
                "wordcount",
                "advlist",
                "lists",
                "indent2em",
                "hr",
                "toolbarsticky",
                "textpattern"
                //...
            ],
            min_height: 300, //编辑区域的最小高度
            fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt 48pt",
            font_formats: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
            powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
            powerpaste_html_import: 'propmt',// propmt, merge, clear
            powerpaste_allow_local_images: true,
            paste_data_images: true,
            images_upload_handler: function (blobInfo, success, failure) {
                var xhr, formData;
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open("POST", "${pageContext.request.contextPath}/util/uploadImage");
                formData = new FormData();
                formData.append("file", blobInfo.blob(), blobInfo.filename());
                xhr.onload = function (e) {
                    var json;
                    if (xhr.status != 200) {
                        failure('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(this.responseText);

                    if (!json || typeof json.location != 'string') {
                        failure('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    success(json.location);
                };
                xhr.send(formData);
            },
            toolbar: [
                'code insertfile undo redo emoticons | formatselect | forecolor backcolor charmap bold italic underline strikethrough hr | fontselect | fontsizeselect | blockquote subscript superscript removeformat |',
                'bullist numlist | alignleft aligncenter alignright alignjustify outdent indent indent2em | link image table'
            ],
            init_instance_callback: function () {
                loading("reset");
                // var htmlStr = "";
                // $("#loading_editor").html(htmlStr);
            },
            // 工具栏吸附
            my_toolbar_sticky: true,
            toolbar_sticky_always: true,
            toolbar_sticky_elem: "nav",
            toolbar_sticky_elem_autohide: false,
            // placeholder
            placeholder: "留下你对本资源的评论吧~"
        });
    }

    function initCommentTinymce(id, text) {
        tinymce.init({
            selector: '#comment-editor-box-'+id,
            contextmenu: "bold copy | link | image | imagetools | table | spellchecker",//上下文菜单
            auto_focus: false,
            menubar: false,
            language: 'zh_CN',
            // force_br_newlines: true,
            // force_p_newlines: false,
            // forced_root_block: "",
            // preformatted: true,
            toolbar_mode: 'sliding',
            branding: false,
            content_style: "img {height:auto;max-width:100%;max-height:100%;}",
            editor_selector: "comment-editor-tinymce-"+id,
            plugins: [
                'powerpaste', // plugins中，用powerpaste替换原来的paste
                'image',
                "autoresize",
                "code",
                "link",
                "charmap",
                "emoticons",
                "table",
                "wordcount",
                "advlist",
                "lists",
                "indent2em",
                "hr",
                "toolbarsticky",
                "textpattern"
                //...
            ],
            min_height: 300, //编辑区域的最小高度
            fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt 48pt",
            font_formats: "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
            powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
            powerpaste_html_import: 'propmt',// propmt, merge, clear
            powerpaste_allow_local_images: true,
            paste_data_images: true,
            images_upload_handler: function (blobInfo, success, failure) {
                var xhr, formData;
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open("POST", "${pageContext.request.contextPath}/util/uploadImage");
                formData = new FormData();
                formData.append("file", blobInfo.blob(), blobInfo.filename());
                xhr.onload = function (e) {
                    var json;
                    if (xhr.status != 200) {
                        failure('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(this.responseText);

                    if (!json || typeof json.location != 'string') {
                        failure('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    success(json.location);
                };
                xhr.send(formData);
            },
            toolbar: [
                'code insertfile undo redo emoticons | formatselect | forecolor backcolor charmap bold italic underline strikethrough hr | fontselect | fontsizeselect | blockquote subscript superscript removeformat |',
                'bullist numlist | alignleft aligncenter alignright alignjustify outdent indent indent2em | link image table'
            ],
            init_instance_callback: function () {
                loading("reset");
                // var htmlStr = "";
                // $("#loading_editor").html(htmlStr);
            },
            // 工具栏吸附
            my_toolbar_sticky: true,
            toolbar_sticky_always: true,
            toolbar_sticky_elem: "nav",
            toolbar_sticky_elem_autohide: false,
            // placeholder
            placeholder: "修改这个评论吧~（请不要超过5000字）"
        });
    }

    // 打开、关闭评论编辑
    function doEdit(id) {
        if (id != 'comment-title'){
            if ($("#comment-editor-" + id).css("display") === "none") {
                // 关闭其他评论编辑框
                for (var i=0; i < commentIds.length; i++) {
                    if (commentIds[i] != id) $("#comment-editor-" + commentIds[i]).css('display', 'none');
                }
                // 初始化并展示该评论编辑框
                initCommentTinymce(id, $("#comment-content-" + id).text)
                $("#comment-editor-" + id).css('display', 'block');

                // 加载
                let comment = JSON.parse(localStorage.getItem('comment'))
                if (comment != null && comment['userId'] == userId && comment['commentId'] == id) {
                    $.tipModal('confirm', 'warning', '有评论编辑草稿，需要加载吗?', function (result) {
                        if (result == true) {
                            tinymce.get("comment-content-" + id).setContent(comment['content']);
                        } else {
                            window.localStorage.removeItem('comment');
                        }
                    });
                }

                // // 开启自动保存
                // window.clearTimeout(time2);
                // edit_comment_id = id;
                // time2 =  setInterval(temp_submit_comment, TimeInterval);
            }
            else if ($("#comment-editor-" + id).css("display") === "block") {
                $.tipModal('confirm', 'warning', '退出编辑将丢失未保存的修订内容，请确认是否退出编辑？', function (result) {
                    if (result == true) {
                        $("#comment-editor-" + id).css('display', 'none');
                    }
                });
            }
        }
    }

    function doFold(mod, id) {
        // mod: 1.展开 / 0.收起
        if (mod == 1) {
            // 显示区域
            $('#comment-content-' + id).css('display', 'block');
            $('#comment-min-' + id).css('display', 'none');
            // 控制按钮
            $('#comment-foldOn-upper-' + id).css('display', 'block');
            $('#comment-foldOff-upper-' + id).css('display', 'none');
            $('#comment-foldOn-lower-' + id).css('display', 'block');
            $('#comment-foldOff-lower-' + id).css('display', 'none');

            // 如果长度太大，就显示下面的链接
            let limitHeight = 200;
            if($("#comment-content-" + id).outerHeight() > limitHeight) {
                $('#comment-links-lower-' + id).css('display', 'block');
            }
        } else {
            // 显示区域
            $('#comment-content-' + id).css('display', 'none');
            $('#comment-min-' + id).css('display', 'block');
            // 控制按钮
            $('#comment-foldOn-upper-' + id).css('display', 'none');
            $('#comment-foldOff-upper-' + id).css('display', 'block');
            $('#comment-foldOn-lower-' + id).css('display', 'none');
            $('#comment-foldOff-lower-' + id).css('display', 'block');

            // 隐藏下面的链接
            $('#comment-links-lower-' + id).css('display', 'none');
        }
    };

    function foldComment() {
        // 评论区折叠高度
        let limitHeight = 200;
        $("#comment-box > div").each(function(){
            let id = $(this).attr('id');
            if (id != 'comment-title') {
                // 若超出限制高度，需要折叠
                if ($("#comment-content-" + id).outerHeight() > limitHeight) {
                    /** ============== 3.0版本：直接限制高度截断，增加css特效样式 ============== */
                    // 去除 style 属性，填充缩略区域
                    let content = $('#comment-content-' + id).html();
                    content = content.replace(/(<p[^>]*?)\sstyle=".*?"/g, '$1');
                    $('#comment-min-' + id).html(content);
                    // 截断
                    $('#comment-min-' + id).css('height', limitHeight.toString() + 'px');
                    // 显示折叠缩略
                    doFold(0, id);

                    /** ============== 2.0版本：不替换<p标签 ============== */
                    // let contentTemp = content.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/(<[^p\/][^>]+?>|<\/[^p][^>]+?>)/g,'');
                    // let contentMin = "";
                    // let cutFlag = 0;
                    // let heightFlag = false;
                    // let availableLength = 250;
                    // while (cutFlag === 0) {
                    //     let pStart = contentTemp.indexOf("<p");
                    //     if (pStart === -1) {
                    //         contentMin += contentTemp.substring(0, availableLength);
                    //         if (availableLength > contentTemp.length) {
                    //             cutFlag = 1; //1.完全显示
                    //         } else {
                    //             cutFlag = 2; //2.在末尾发生截断
                    //         }
                    //     } else {
                    //         let pStartEnd = contentTemp.indexOf(">");
                    //         let pEnd = contentTemp.indexOf("</p>");
                    //         let pLength = (pEnd - pStartEnd + pStart);
                    //         if (pLength > availableLength || pEnd === -1) {
                    //             cutFlag = 3; //3.在段中发生截断
                    //         } else {
                    //             availableLength -= pLength;
                    //             contentMin += contentTemp.substring(0, pEnd + 4);
                    //             contentTemp = contentTemp.substring(pEnd + 4);
                    //         }
                    //     }
                    // }
                    // contentMin += " ...";
                    // //填充缩略区域
                    // $('#comment-min-' + id).html(contentMin);
                    // if ($('#comment-min-' + id).outerHeight() < $(this).outerHeight()) {
                    //     heightFlag = true;
                    // }

                    /** ============== 1.0版本：直接替换全部标签 ============== */
                    // let contentMin = content.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'')
                    //     .replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ').substring(0, 400) + '...';
                    // //填充缩略区域
                    // $('#comment-min-' + id).html(contentMin);
                } else {
                    // 长度不长，完全显示
                    doFold(1, id);
                }
            }
        });
    }

    /*
    function addComment(com) {
        console.log(com)
        // 创建评论内容的 HTML
        var commentHTML =
            '<div class="resource-comment" id="' +
            com.id +
            '">' +
            '<div class="col-lg-12">' +
            // 评论头像
            '<div class="resource-comment-img">' +
            '<img src="/assets/images/profilePic/' +
            com.picName +
            '">' +
            '</div>' +
            // 评论内容
            '<div class="resource-comment-cont">' +
            '<div class="resource-comment-head row">' +
            // 评论用户
            '<a href="/myresource?userId=' +
            com.userId +
            '" class="resource-comment-name" id="comment-username-' +
            com.id +
            '">' +
            com.userName +
            '</a>' +
            // 评论操作
            // 删除-折叠按钮
            '<div style="float: right">' +
            '<a type="button" class="resource-comment-name font-text-darkgray" style="text-align: right;text-decoration: underline" id="comment-editButton-' +
            com.id +
            '" onclick="doEdit(' +
            com.id +
            ')">' +
            '编辑</a>' +
            '<div class="resource-comment-name">&nbsp|&nbsp</div>' +
            '<a type="button" class="resource-comment-name font-text-darkgray" style="text-align: right;text-decoration: underline" onclick="deleteComment(' +
            com.id +
            ')">' +
            '删除</a>' +
            '<div class="resource-comment-name">&nbsp|&nbsp</div>' +
            '<a type="button" class="resource-comment-name font-text-darkgray" style="float: right;text-decoration: underline" id="comment-foldOn-' +
            com.id +
            '" href="javascript:doFold(0, ' +
            com.id +
            ')" style="display: block">' +
            '折叠</a>' +
            '<a type="button" class="resource-comment-name font-text-darkgray" style="float: right;text-decoration: underline" id="comment-foldOff-' +
            com.id +
            '" href="javascript:doFold(1, ' +
            com.id +
            ')" style="display: none">' +
            '展开</a>' +
            '</div>' +
            '</div>' +
            // 正常显示
            '<div class="resource-comment-text" id="comment-content-' +
            com.id +
            '">' +
            com.content +
            '</div>' +
            // 折叠显示
            '<div class="resource-comment-text resource-comment-gradient" style="display: none;" id="comment-min-' +
            com.id +
            '">' +
            '</div>' +
            // 时间-编辑-折叠按钮
            '<div class="resource-comment-date row" id="comment-bottomOff-' +
            com.id +
            '">' +
            // 时间
            com.time +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div class="resource-comment" id="comment-editor-' +
            com.id +
            '" style="display: none">' +
            '<div id="comment-editor-box-' +
            com.id +
            '" autofocus></div>' +
            '<button id="updateCommentButton-' +
            com.id +
            '" class="re-btn re-label-child pull-right" onclick="updateComment(' +
            com.id +
            ')">' +
            '更新评论' +
            '</button>' +
            '<br>' +
            '<br>' +
            '</div>';
        console.log(commentHTML);

        // 将评论内容添加到 comments 这个 div 的开头
        $("#add-comment").append(commentHTML);
        doFold(0, com.id);
    }
     */

    initTinymce();
    foldComment();
    //loadTempComment();

    curPage = 1;
    _commentTotal = ${commentTotal};
    _thisPageTotal = ${commentList.size()};

    // $(document).ready(function () {
    //
    // })

    //

</script>

<script>
    // 获取所有id带有"comment-editor-box-"前缀的控件的id中的数字部分
    function getCommentEditorBoxIds() {
        var elements = document.querySelectorAll('[id^="comment-editor-box-"]');
        var ids = [];
        for (var i = 0; i < elements.length; i++) {
            var idValue = elements[i].id.replace('comment-editor-box-', '');
            ids.push(idValue);
        }
        return ids;
    }

    // box的id和评论id对等
    var commentIds = getCommentEditorBoxIds();
    /*
        // 根据commentEditorBoxIds创建相同大小的初始化状态数组
        function createInitializationStatusArray(ids) {
            var initializationStatus = [];
            for (var i = 0; i < ids.length; i++) {
                initializationStatus.push(false); // 初始化状态设置为false
            }
            return initializationStatus;
        }

        // 调用函数并打印结果
        var tinymiceStatusArray = createInitializationStatusArray(commentEditorBoxIds);
        console.log(tinymiceStatusArray);
         */
</script>
